package controller

import (
	"strconv"
	"webstack/model"

	"github.com/gin-gonic/gin"
)

func AddWebCategory(c *gin.Context) {
	var m model.WebCategory
	c.ShouldBind(&m)
	id, err := m.Add()
	if err != nil {
		c.JSON(200, gin.H{"id": 0, "errCode": 10, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"id": id, "errCode": 0, "errMsg": ""})
	}
}

func DeleteWebCategory(c *gin.Context) {
	var m model.WebCategory
	c.ShouldBind(&m)
	err := model.DeleteWebCategory(m.ID)
	if err != nil {
		c.JSON(200, gin.H{"errCode": 25, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"errCode": 0, "errMsg": ""})
	}
}

func UpdateWebCategory(c *gin.Context) {
	var m model.WebCategory
	c.ShouldBindJSON(&m)
	err := m.Update()
	if err != nil {
		c.JSON(200, gin.H{"errCode": 36, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"errCode": 0, "errMsg": ""})
	}
}

func GetWebCategory(c *gin.Context) {
	_, withPrivate := c.Get("token")

	items, err := model.GetWebCategory(withPrivate)
	if err != nil {
		c.JSON(200, gin.H{"items": nil, "errCode": 34, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"items": items, "errCode": 0, "errMsg": ""})
	}
}

func GetSubsWebCategory(c *gin.Context) {
	_, withPrivate := c.Get("token")
	id, _ := strconv.Atoi(c.DefaultQuery("id", "0"))
	item, err := model.GetWebSubCategory(id, withPrivate)
	if err != nil {
		c.JSON(200, gin.H{"item": nil, "errCode": 34, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"item": item, "errCode": 0, "errMsg": ""})
	}
}

func GetAllWebCategories(c *gin.Context) {
	items, err := model.GetAllWebCategories()
	if err != nil {
		c.JSON(200, gin.H{"items": nil, "errCode": 34, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"items": items, "errCode": 0, "errMsg": ""})
	}
}

func GetAllWebCategoryData(c *gin.Context) {
	_, withPrivate := c.Get("token")
	items, err := model.GetAllWebCategoryData(withPrivate)
	if err != nil {
		c.JSON(200, gin.H{"items": nil, "errCode": 34, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"items": items, "errCode": 0, "errMsg": ""})
	}
}

func SetWebCategoryOrd(c *gin.Context) {
	var m model.WebCategory
	c.ShouldBind(&m)
	err := model.SetWebCategoryOrd(m.ID, m.Ord)
	if err != nil {
		c.JSON(200, gin.H{"errCode": 67, "errMsg": err.Error()})
	} else {
		c.JSON(200, gin.H{"errCode": 0, "errMsg": ""})
	}
}
